package com.chat.api.handler;

import com.chat.GroupInfoServiceInterface;
import com.chat.api.dto.ChatMessageDTO;
import com.chat.biz.service.Impl.ChatMessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.AccessType;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {

    private static final Map<String, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private ChatMessageService chatMessageService;  // 消息入库服务
    @DubboReference
    private GroupInfoServiceInterface groupService;              // 群成员查询服务

    // 线程池：用于群聊异步转发
    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    /** 1️⃣ 连接建立 */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String query = session.getUri().getQuery(); // userId=1
        String userId = query != null ? query.split("=")[1] : null;
        if (userId == null) {
            session.close(CloseStatus.BAD_DATA);
            return;
        }
        SESSION_POOL.put(userId, session);
        log.info("[WebSocket] 用户 {} 上线，总数={}", userId, SESSION_POOL.size());
    }

    /** 2️⃣ 接收消息（私聊 / 群聊） */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        ChatMessageDTO dto = MAPPER.readValue(message.getPayload(), ChatMessageDTO.class);

        // 统一入库
        chatMessageService.saveMessage(dto);

        if (dto.getChatType() == 0) {
            // 👉 私聊
            WebSocketSession receiver = SESSION_POOL.get(dto.getReceiverId());
            if (receiver != null && receiver.isOpen()) {
                receiver.sendMessage(new TextMessage(MAPPER.writeValueAsString(dto)));
            } else {
                log.info("用户 {} 不在线，私聊消息转离线", dto.getReceiverId());
            }
        } else if (dto.getChatType() == 1) {
            // 👉 群聊（异步发送）
            executor.submit(() -> {
                List<String> memberIds = groupService.getGroupMemberIds(dto.getReceiverId());
                for (String memberId : memberIds) {
                    if (memberId.equals(dto.getSenderId())) continue; // 跳过自己
                    WebSocketSession memberSession = SESSION_POOL.get(memberId);
                    if (memberSession != null && memberSession.isOpen()) {
                        try {
                            memberSession.sendMessage(new TextMessage(MAPPER.writeValueAsString(dto)));
                        } catch (Exception e) {
                            log.warn("发送给 {} 失败", memberId, e);
                        }
                    }
                }
            });
        }
    }

    /** 3️⃣ 连接关闭 */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        SESSION_POOL.values().removeIf(sess -> sess.getId().equals(session.getId()));
        log.info("[WebSocket] 连接关闭，当前在线={}", SESSION_POOL.size());
    }

    /** 4️⃣ 异常处理 */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.error("[WebSocket] 传输异常", exception);
    }
}
